package Binary_tree;

// 给定一棵二叉树的头节点head，可以从树中的任何一点出发，如果走的话只能向下，
// 也可以选择随时停止，所形成的轨迹叫做一条路径，路径上所有值的累加和叫作路径和。求这棵树上的最大路径和。
public class Code04_MaxPathSum {

    public static class Node {
        public int value;
        public Node left;
        public Node right;

        public Node(int val) {
            value = val;
        }
    }

    public static class Info{
        public int fromHeadMaxPathSum;
        public int allMaxPathSum;

        public Info(int f, int a){
            fromHeadMaxPathSum = f;
            allMaxPathSum = a;
        }
    }

    public static Info process(Node x){
        if (x == null){
            return null;
        }
        Info leftInfo = process(x.left);
        Info rightInfo = process(x.right);
        int p1 = x.value;
        int p2 = x.value + (leftInfo == null ? 0 : leftInfo.fromHeadMaxPathSum);
        int p3 = x.value + (rightInfo == null ? 0 : rightInfo.fromHeadMaxPathSum);

        int fromHeadMaxPathSum = Math.max(Math.max(p1, p2), p3);
        int allMaxPathSum = fromHeadMaxPathSum;
        if (leftInfo != null){
            allMaxPathSum = Math.max(allMaxPathSum, leftInfo.allMaxPathSum);
        }
        if (rightInfo != null){
            allMaxPathSum = Math.max(allMaxPathSum, rightInfo.allMaxPathSum);
        }
        return new Info(fromHeadMaxPathSum, allMaxPathSum);
    }

    public static void main(String[] args){
        Node head = new Node(4);
        head.left = new Node(1);
        head.left.right = new Node(5);
        head.right = new Node(7);
        head.right.left = new Node(3);
        System.out.println(process(head).allMaxPathSum);
    }
}
